import { defineStore } from 'pinia'
import { verifyCode, getKey, login, getUserInfo, register, getDeveloperOverview, getDescString, getOpenToken } from '@/api/login'
import { getToken, setToken, setOpenToken, removeToken } from '@/utils/auth'
import RSAEncrypt from '@/utils/encrypt/rsa'
import to from 'await-to-js'
interface UserInfo {
  userId: string
  username: string
  email: string
  phoneNo: string
}

export const useUserStore = defineStore({
  id: 'userState',
  state: () => ({
    token: getToken() || '',
    userInfo: {} as UserInfo | null,
    isDeveloper: false,
    openToken: ''
  }),
  getters: {
    isLogin: (state) => !!state.userInfo?.userId
  },
  actions: {
    // 登录
    login(userInfo: any) {
      return new Promise(async (resolve, reject) => {
        const { code, username, password } = userInfo
        const [err1, res1] = await to(verifyCode(code))
        if (err1) {
          reject(err1)
          return
        }
        if (res1.retCode !== '000000') {
          reject(res1.retMsg)
          return
        }
        const [err2, res2] = await to(getKey())
        if (err2) {
          reject(err2)
          return
        }
        if (res2.retCode !== '000000') {
          reject(res2.retMsg)
          return
        }
        const { exponent, modulus } = res2.object
        const data = {
          userId: RSAEncrypt(username, exponent, modulus),
          passwd: RSAEncrypt(password, exponent, modulus)
        }
        const [err3, res3] = await to(login(data))
        if (err3) {
          reject(err3)
          return
        }
        if (res3.retCode !== '000000') {
          reject(res3.retMsg)
          return
        }
        if (res3.token) {
          this.token = res3.token
          setToken(res3.token)
        }
        resolve(res3)
      })
    },
    // 注册
    register(userInfo: any) {
      return new Promise(async (resolve, reject) => {
        const { code, username, password } = userInfo
        const [err2, res2] = await to(getKey())
        if (err2) {
          reject(err2)
          return
        }
        if (res2.retCode !== '000000') {
          reject(res2.retMsg)
          return
        }
        const { exponent, modulus } = res2.object
        const data = {
          userId: RSAEncrypt(username, exponent, modulus),
          passwd: RSAEncrypt(password, exponent, modulus),
          code
        }
        const [err3, res3] = await to(register(data))
        if (err3) {
          reject(err3)
          return
        }
        if (res3.retCode !== '000000') {
          reject(res3.retMsg)
          return
        }
        if (res3.token) {
          this.token = res3.token
          setToken(res3.token)
        }
        resolve(res3)
      })
    },
    // 获取用户信息
    getInfo() {
      return new Promise(async (resolve, reject) => {
        const [err, res] = await to(getUserInfo())
        if (err || res.retCode !== '000000') {
          reject(res.retMsg || err)
          return
        }
        const [err1, res1] = await to(getDeveloperOverview())
        if (err1 || res1.retCode !== '000000') {
          reject(res1.retMsg || err)
          return
        }
        this.userInfo = res.data
        this.isDeveloper = res1.data.joinSuccess
        this.GetUserOpenToken()
        // 获取购物车信息
        // const [err2, res2] = await to(cartList({ currentPage: 1, pageSize: 10000 }))
        // if (err2 || res2.retCode !== '000000') {
        //   reject(res2.retMsg || err)
        //   return
        // }
        // dispatch('initCart', res2.data.list)
        resolve(res)
      })
    },
    // 获取登陆人能力聚合平台的token
    GetUserOpenToken() {
      return new Promise(async (resolve) => {
        const [err, res] = await to(getDescString())
        if (err || !res.object) return
        const [err2, res2] = await to(getOpenToken(res.object))
        if (err2 || !res2.data) return
        this.openToken = res2.data?.identitytoken
        setOpenToken(this.openToken)
        resolve(res)
      })
    },
    // 退出
    logout() {
      return new Promise((resolve) => {
        this.userInfo = null
        this.token = ''
        removeToken()
        resolve('success')
      })
    }
  }
})
